<template>
<!--  <el-select v-model="subAccount" filterable clearable placeholder="请选择子账户" @change="handleSetCategory">-->
<!--    <el-option-->
<!--      v-for="item in accounts"-->
<!--      :key="item.id"-->
<!--      :label="item.username"-->
<!--      :value="item.id">-->
<!--    </el-option>-->
<!--  </el-select>-->
  <el-cascader
    v-model="subAccount"
    :options="accounts"
    :props="optionProps"
    :show-all-levels="false"
    @change="handleSetsSubAccount"
    placeholder="请选择子账户"
    ref="sub-account-selector" clearable filterable style="padding-top: 8px"></el-cascader>
</template>

<script>
import {listSubAccounts} from "@/api/user";

export default {
  name: 'SubAccountSelect',
  data() {
    return {
      accounts: this.$store.getters.accounts,
      subAccount: null,
      optionProps: { //配置节点
        value: 'id',
        label: 'username',
        children: 'sub_accounts',
        checkStrictly:true,
        lazy: true,
        lazyLoad:this.loadSubAccounts,
      },
    }
  },
  created() {
    this.subAccount = this.$store.getters.subAccount
  },
  methods: {
    handleSetsSubAccount() {
      const subAccount = this.subAccount.length > 0 ? this.subAccount[this.subAccount.length - 1] : 0
      this.$store.dispatch('user/setSubAccount', subAccount)
      this.refreshView()
    },
    loadSubAccounts(node, resolve){
      const { level } = node;
      if (level === 0) {
        // 根节点不需要懒加载，直接返回
        return resolve([]);
      }
      const parentId = node.value;

      if(parentId === 0) {
        return resolve([]);
      }

      listSubAccounts({pid: parentId }).then(response => {
        if(response.code === 20000) {
          const nodes = response.data.map(item => ({
            id: item.id,
            username: item.username,
            leaf: false
          }));
          resolve(nodes);
        }else{
          return resolve([]);
        }
      });
    },
    refreshView() {
      // In order to make the cached page re-rendered
      this.$store.dispatch('tagsView/delAllCachedViews', this.$route)

      const { fullPath } = this.$route

      this.$nextTick(() => {
        this.$router.replace({
          path: '/redirect' + fullPath
        })
      })
    }
  }

}
</script>
